package com.example.ketangpai_backend.utils;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;


@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取 token
        String token = request.getHeader("token");


        if (token == null || token.isEmpty()) {
            System.out.println("未登录");

            return handleUnauthorized(response, JsonResult.error("未登录"));
        }


        // 验证 token 的有效性
        if (!isValidToken(token)) {
            System.out.println("无效");
            return handleUnauthorized(response, JsonResult.error("token 无效"));

        }


        // token 有效，继续处理请求
        System.out.println("有效");
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理完毕后调用
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完全处理完毕后调用
    }


    private boolean isValidToken(String token) {
        try {
            Claims claims = JwtUtil.parseJWT(token);
            // 可以添加更多的检查，例如检查有效期
            Date expiration = claims.getExpiration();
            if (expiration.before(new Date())) {
                return false;
            }
            // 检查其他信息，例如用户信息
            // String username = (String) claims.get("username");
            // if (username == null || username.isEmpty()) {
            //     return false;
            // }
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    private boolean handleUnauthorized(HttpServletResponse response, JsonResult<?> result) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getWriter().write(JSONObject.toJSONString(result));
        return false;
    }
}